package com.core.framework.db;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.sql.DataSource;
import com.core.framework.db.jdbc.annotation.DTO;
import com.core.framework.tools.StringUtils;
import com.core.framework.tools.Tools;
import com.core.log.Log;
import com.util.AppUtils;
/**
 * DTO 生成类
 * @author 刘利
 * @since Jun 27, 2012
 */
public class DBTools{
	public static String[] getTablePK(Connection conn, String tableCodes) throws Exception {
        String[] resultArray = null;
        DatabaseMetaData dbmd = conn.getMetaData();
        ResultSet rs = dbmd.getPrimaryKeys(null, null, tableCodes);
        String tempPK = "";
        if (rs != null)
            while (rs.next()) {
                tempPK = rs.getString("COLUMN_NAME") + ",";
            }
        resultArray = tempPK.split(",");
        if (tempPK.length() < 1) {
            resultArray = null;
        }
        rs.close();
        return resultArray;
    }
	
	 public static  void getDTO(String tableName) {
	        String sql = "select * from " + tableName + " where 1=2";
	        ResultSet rs;
	        try {
	        	DataSource ds = (DataSource) AppUtils.getBean("dataSource");
	            String pks[] = null;
	            try {
	                pks = getTablePK(ds.getConnection(), tableName);
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	            ArrayList<String> pkList = new ArrayList<String>();
	            if (pks != null)
	                for (int i = 0; i < pks.length; i++) {
	                    pkList.add(pks[i]);
	                }
	            rs = ds.getConnection().createStatement().executeQuery(sql);
	            ResultSetMetaData m = rs.getMetaData();
	            int columnCount = m.getColumnCount();
	            StringBuffer buffColumns = new StringBuffer();
	            StringBuffer buffUpdateColumns = new StringBuffer();
	            StringBuffer buffInsertColumns = new StringBuffer();
	            StringBuffer buffSelectColumns = new StringBuffer();
	            StringBuffer buffListColumns = new StringBuffer();
	            for (int i = 0; i < columnCount; i++) {
	                String name = m.getColumnName(i + 1);
	                buffColumns.append("\"" + name + "\",");
	                buffSelectColumns.append("\"" + name + "\",");
	                buffListColumns.append("\"" + name + "\",");
	                if (!pkList.contains(name)) {
	                    if (!"updateTime".equals(name))
	                        buffInsertColumns.append("\"" + name + "\",");
//	                    if (!"createTime".equals(name))
//	                        if (!"createUser".equals(name))
//	                            if (!"userName".equals(name))
	                                buffUpdateColumns.append("\"" + name + "\",");
	                }
	            }
	        
	            String str = "@" + DTO.class.getName() + "(  ";
	            
	            str = str + "\tucolumns={" + buffUpdateColumns + "},\n";
	            str = str + "\ttableName= \"" + tableName + "\" \n";
	            if (pks != null && pks.length == 1)
	                str = str + "\t  , pkey= \"" + pks[0] + "\" \n";//此处有一个逻辑bug 没有对2个以上主键进行支持
	            str = str + ")\n";
	            str = str + "\n";
	            Log.debug(str);
	            for (int i = 0; i < columnCount; i++) {
	                String type = m.getColumnClassName(i + 1);
	                //Log.debug(type);
	                String name = m.getColumnName(i + 1);
	                //Log.debug("\n\tprivate " + beanType(type) + " " + Tools.toOntRowName(name) + ";");
	                //str = str + type;
	                //str = str + "\n\tprivate " + beanType(type) + " " + Tools.toOntRowName(name) + ";\n";
	                str = str + "\n\tprivate " + beanType(type) + " " + name + ";\n";
	            }
	            for (int i = 0; i < columnCount; i++) {
	                String type = m.getColumnClassName(i + 1);
	                String name0 = m.getColumnName(i + 1);
	                //String name = Tools.toOntRowName(name0);
	                String name = name0;
	                {
	                	str = str + "\n\tpublic " + beanType(type) + " get" + capitalize(name) + "(){\n\t return  " + name + ";\n\t}";
	                    str = str + "\n\tpublic void  set" + capitalize(name) + "( " + beanType(type) + " " + name + " ){\n\t this." + name + "=" + name + ";\n\t}";
	                	//Log.debug("\tpublic " + beanType(type) + " get" + capitalize(name) + "(){\n\t return  " + name + ";\n\t}");
	                    //Log.debug("\tpublic void  set" + capitalize(name) + "( " + beanType(type) + " " + name + " ){\n\t this." + name + "=" + name + ";\n\t}");
	                }
	            }
	            System.out.println(str);
	        } catch (SQLException e) {
	            e.printStackTrace();
	        }
	        
	    }
	    
	    
	    public void genSorlBean(String tableName) {
	        String sql = "select * from " + tableName + " where 1=2";
	        ResultSet rs;
	        try {
	        	DataSource ds = (DataSource) AppUtils.getBean("dataSource");
	            String pks[] = null;
	            try {
	                pks = getTablePK(ds.getConnection(), tableName);
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	            ArrayList<String> pkList = new ArrayList<String>();
	            if (pks != null)
	                for (int i = 0; i < pks.length; i++) {
	                    pkList.add(pks[i]);
	                }
	            rs = ds.getConnection().createStatement().executeQuery(sql);
	            ResultSetMetaData m = rs.getMetaData();
	            int columnCount = m.getColumnCount();
	            for (int i = 0; i < columnCount; i++) {
	                String type = m.getColumnClassName(i + 1);
	                String name = m.getColumnName(i + 1);
	                Log.debug("\n\tprivate " + beanType(type) + " " + Tools.toOntRowName(name) + ";");
	            }
	        } catch (SQLException e) {
	            e.printStackTrace();
	        }
	    }
	    public static String capitalize(String name) {
	        if (name == null || name.length() == 0) {
	            return name;
	        }
	        // 针对aB模式进行处理
	        if (name.length() > 1) {
	            if (Character.isUpperCase(name.charAt(1)) && Character.isLowerCase(name.charAt(0))) {
	                return name;
	            }
	        }
	        return StringUtils.capitalize(name);
	    }
	    public static String beanType(String type) {
	        if ("".equals(type)) {} else if ("java.lang.Integer".equals(type)) {
	            return "Integer";
	        } else if ("java.lang.Long".equals(type)) {
	            return "Long";
	        } else if ("java.lang.Boolean".equals(type)) {
	            return "Boolean";
	        } else if ("java.sql.Timestamp".equals(type)) {
	            return "java.util.Date";
	        } else if ("java.sql.Date".equals(type)) {
	            return "java.util.Date";
	        } else if ("java.lang.String".equals(type)) {
	            return "String";
	        } else if ("java.lang.Double".equals(type)) {
	            return "double";
	        } else if ("java.math.BigDecimal".equals(type)) {
	            return "java.math.BigDecimal";
	        } else if ("java.sql.Clob".equals(type)) {
	            return "String";
	        } else {
	            return type;
	        }
	        return type;
	    }
	public static void main(String[] args)
	{
		DBTools.getDTO("SS_User");
	}
	
}
